﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EntityFrameworks.Data.Core;
using System.Web.Mvc;
using EntityFrameworks.Entity.Core;
using IRepository.Core;

namespace Common.Background.Controllers
{
    /// <summary>
    /// Controller base class
    /// </summary>
    public abstract class BaseController : System.Web.Mvc.Controller
    {
        #region Fields
        IExtensionRepository<WebManageMenus> _menuRepository;
        IExtensionRepository<WebManageUsers> _userRepository;
        IExtensionRepository<WebManageRoles> _roleRepository;
        IExtensionRepository<WebDepartments> _deptRepository;
        #endregion

        #region Properties
        /// <summary>
        /// 工作单元对象，由派生类通过构造方法创建对象，并对派生类公开访问
        /// </summary>
        protected IUnitOfWork UnitOfWork { get; private set; }
        /// <summary>
        /// 菜单操作对象
        /// </summary>
        protected IExtensionRepository<WebManageMenus> MenuRepository
        {
            get
            {
                return _menuRepository ?? (_menuRepository = new BackgroundBase<WebManageMenus>(UnitOfWork));
            }
        }
        /// <summary>
        /// 用户操作对象
        /// </summary>
        protected IExtensionRepository<WebManageUsers> UserRepository
        {
            get
            {
                return _userRepository ?? (_userRepository = new BackgroundBase<WebManageUsers>(UnitOfWork));
            }
        }
        /// <summary>
        /// 角色操作对象
        /// </summary>
        protected IExtensionRepository<WebManageRoles> RoleRepository
        {
            get
            {
                return _roleRepository ?? (_roleRepository = new BackgroundBase<WebManageRoles>(UnitOfWork));
            }
        }
        /// <summary>
        /// 部门操作对象
        /// </summary>
        protected IExtensionRepository<WebDepartments> DeptRepository
        {
            get
            {
                return _deptRepository ?? (_deptRepository = new BackgroundBase<WebDepartments>(UnitOfWork));
            }
        }
        /// <summary>
        /// 每页显示的记录数
        /// </summary>
        protected int PageSize { get; set; }


        #endregion

        #region Constructors

        protected BaseController(IUnitOfWork iUnitOfWork)
        {
            UnitOfWork = iUnitOfWork ?? new backgroundEntities();
            PageSize = 20;
        }

        protected BaseController()
            : this(null)
        {

        }
        #endregion

        #region Methods
        /// <summary>
        /// 加载底层简单GURD操作
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        protected IExtensionRepository<TEntity> LoadRepository<TEntity>() where TEntity : class
        {
            return UnitOfWork == null
                ? new BackgroundBase<TEntity>()
                : new BackgroundBase<TEntity>(UnitOfWork);
        }

        /// <summary>
        /// 根据字符串主键，得到一组实体列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="iCompleteRepository"></param>
        /// <param name="formIdArr">从表单传递过来的ID数组</param>
        /// <returns></returns>
        protected virtual ICollection<T> GetEntitiesByIdArr<T>(IExtensionRepository<T> iCompleteRepository, string formIdArr)
            where T : class, IEntity
        {
            var idArr = new List<int>();
            if (formIdArr != null)
            {
                formIdArr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(i => idArr.Add(int.Parse(i)));

                return iCompleteRepository.GetModel()
                                     .ToList()
                                     .Where(i => idArr
                                     .Contains(i.PrimaryKey))
                                     .ToList();
            }
            return null;
        }
        #endregion

        #region Properties For Current LogOn user

        protected int Current_UserID
        {
            get
            {
                return System.Web.HttpContext.Current.Session["UserID"] == null
                    ? 0
                    : Convert.ToInt32(System.Web.HttpContext.Current.Session["UserID"]);
            }
            set { System.Web.HttpContext.Current.Session["UserID"] = value; }
        }

        /// <summary>
        /// 当前登陆的用户ID
        /// </summary>
        protected int CurrentUserId
        {
            get
            {
                return System.Web.HttpContext.Current.Session["UserID"] == null
                    ? 0
                    : Convert.ToInt32(System.Web.HttpContext.Current.Session["UserID"]);
            }
            set { System.Web.HttpContext.Current.Session["UserID"] = value; }
        }

        /// <summary>
        /// 当前登陆的用户名
        /// </summary>
        protected string CurrentUserName
        {
            get
            {
                return System.Web.HttpContext.Current.Session["UserName"] == null
                    ? string.Empty
                    : System.Web.HttpContext.Current.Session["UserName"].ToString();
            }
            set { System.Web.HttpContext.Current.Session["UserName"] = value; }
        }

        /// <summary>
        /// 操作权限
        /// </summary>
        protected int CurrentOperatorAuthority
        {
            get
            {
                return System.Web.HttpContext.Current.Session["OperatorAuthority"] == null
                    ? 0
                    : Convert.ToInt32(System.Web.HttpContext.Current.Session["OperatorAuthority"]);
            }
            set { System.Web.HttpContext.Current.Session["OperatorAuthority"] = value; }
        }
        #endregion

        #region Virtual Methods
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //var action = filterContext.Result as ViewResult;
            //if (action != null
            //    && !masterControllerArr.Contains(filterContext.RouteData.Values["controller"].ToString()
            //    , new StringComparisonIgnoreCase()))
            //{
            //    if (DateTime.Now.Second % 2 == 0)
            //        action.MasterName = "_Layout";
            //    else
            //        action.MasterName = "_LayoutRed";
            //}
            base.OnActionExecuted(filterContext);
        }
        #endregion

        #region Fields
        private string[] masterControllerArr = { "System" };
        #endregion
    }



}